const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}


const formatSeconds = theTime => {
  let theTime1 = 0
  let theTime2 = 0
  if (theTime > 60) {
    theTime1 = parseInt(theTime / 60)
    theTime = parseInt(theTime % 60)
    if (theTime1 > 60) {
      theTime2 = parseInt(theTime1 / 60)
      theTime1 = parseInt(theTime1 % 60)
    }
  }
  let result = '' + parseInt(theTime) + '秒'
  if (theTime1 > 0) {
    result = '' + parseInt(theTime1) + '分' + result
  }
  if (theTime2 > 0) {
    result = '' + parseInt(theTime2) + '小时' + result
  }
  return result
}

var CryptoJS = require('./AES.js');
var _KEY = "";//32位
var _IV = "" ;//16位    //这个key和偏移量都是后台给的数据

//字符串加密方法
function encrypt(str){
    var key = CryptoJS.enc.Utf8.parse(_KEY);
    var iv = CryptoJS.enc.Utf8.parse(_IV);
    var encrypted = '';
    var srcs = CryptoJS.enc.Utf8.parse(str);
    encrypted = CryptoJS.AES.encrypt(srcs,key,{
       iv:iv,
       mode:CryptoJS.mode.CBC,
       padding:CryptoJS.pad.Pkcs7
    })
    return encrypted.ciphertext.toString();
}

//字符串解密方法
function decrypt(str){
    var key = CryptoJS.enc.Utf8.parse(_KEY);
    var iv = CryptoJS.enc.Utf8.parse(_IV);
    var encryptedHexStr = CryptoJS.enc.Hex.parse(str);
    var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    var decrypt = CryptoJS.AES.decrypt(srcs,key,{
        iv:iv,
        mode:CryptoJS.mode.CBC,
        padding:CryptoJS.pad.Pkcs7
    }) 
    var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
}

module.exports = {
  formatSeconds: formatSeconds,
  formatTime: formatTime,
  decrypt:decrypt,
  encrypt:encrypt
}